package com.imooc.mvcdemo.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * spring mvc 拦截器的实现
 */
public class TestInterceptor implements HandlerInterceptor {
	/**
	 * 请求结束时调用的方法 主要用于像资源的销毁, 流的关闭等
	 */
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		System.out.println("aterCompletion");

	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		System.out.println("postHandle");
		/**
		 * 可以通过 ModelAndView arg3 改变显示的视图 或 改变发往视图的方法
		 */

		arg3.addObject("msg", "这里传回被拦截器修改后的消息");
		// 原 ModelAndView 中 msg: "从viewAll 方法中传回视图的消息"

		arg3.setViewName("/hello2.jsp");
		// 原: ModelAndView setViewName("/hello1.jsp")

	}

	/**
	 * 返回值: 表示我们是否需要将当前的请求拦截下来 <br>
	 * false: 终止请求 <br>
	 * true: 继续请求 Object org2 : 被拦截请求的目标对象
	 */
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		System.out.println("preHandle");

		return true;
	}

}
